package com.yang.yangarmy.utils;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class PingUtil {

    public static int getPing(Player player) {
        try {
            // 获取 CraftPlayer 类
            Class<?> craftPlayerClass = Class.forName("org.bukkit.craftbukkit." + getServerVersion() + ".entity.CraftPlayer");
            // 获取 getHandle 方法
            Method getHandleMethod = craftPlayerClass.getMethod("getHandle");
            // 调用 getHandle 方法获取 EntityPlayer 对象
            Object entityPlayer = getHandleMethod.invoke(player);
            // 获取 ping 字段
            Field pingField = entityPlayer.getClass().getDeclaredField("ping");
            // 设置 ping 字段可访问
            pingField.setAccessible(true);
            // 获取玩家的 ping 值
            int ping = pingField.getInt(entityPlayer);
            return ping;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static String getServerVersion() {
        return Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
    }
}